package com.hjy.product.web;

import com.hjy.common.utils.R;
import com.hjy.product.entity.CategoryEntity;
import com.hjy.product.service.CategoryService;
import com.hjy.product.vo.categoryVo.category2Level;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @RequestMapping({"/","/index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> list = categoryService.getCategoryLevel1();
        // 前缀和后缀都被 thymeleaf 配置好了
        // classpath:/templates/ + xxx + .html
        model.addAttribute("categories",list);
        return "index";
    }

    @ResponseBody
    @RequestMapping("index/catalog.json")
    public Map<String, List<category2Level>> categoryList() {
        return categoryService.getCategoryList();
    }

    @ResponseBody
    @RequestMapping("/index/hello")
    public R hello() throws InterruptedException {

        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();
        String str = "";
        try {
            Thread.sleep(20000);
            str = UUID.randomUUID().toString();
        }finally {
            lock.unlock();
        }
        return R.ok().put("data",str);
    }

}
